<?php

namespace App\Miya\Middlewares;

use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Miya\Models\UserView as UserViewModel;

class UserView
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //本地测试,不记录uv
        if (request()->getClientIp() == '127.0.0.1') {
            return $next($request);
        }

        $data = [
            'time' => (int)(time() / config('miya.view_frequency')),
            'ip' => request()->getClientIp(),
        ];

        $key = sprintf('uv_%s', md5(json_encode($data)));
        if (!Cache::has($key)) {
            $count = UserViewModel::where('ip', $data['ip'])
                ->where('time', 'like', now()->format('Y-m-d %'))
                ->count();
            if ($count < config('miya.ip_day_request_max_count')) {
                Cache::add($key, 1, config('miya.view_frequency'));

                $data['time'] = now()->format('Y-m-d H:i:s');
                $data['referer_url'] = request()->server('HTTP_REFERER');
                $data['url'] = request()->url();

                UserViewModel::insertOrIgnore($data);
            }
        }
        return $next($request);
    }
}
